import { keyboardKey } from "@testing-library/user-event";
import { nanoid } from "nanoid";
import React, { useRef, useState } from "react";
import { useDispatch } from "react-redux";
import { addTodo } from "../../store/actions/todoList";
import "./index.css";
export default function MyHeader() {
  const [show, setShow] = useState(false);
  const inp = useRef<HTMLInputElement>(null);
  const dispatch = useDispatch();
  const submit = () => {
    const content = inp.current?.value!.trim();
    if (!content?.length) {
      alert("请输入内容");
      return;
    }
    const item = {
      id: nanoid(),
      content,
      complete: false,
      time: Date.now(),
    };
    dispatch(addTodo(item));
    inp.current!.value = "";
    setShow(!show);
  };
  const keySubmit = (event: keyboardKey) => {
    if (event.code?.toLocaleLowerCase() === "enter") {
      submit();
    }
  };
  return (
    <div className="head">
      <h3>事件待办</h3>
      <span className="icon" onClick={() => setShow(!show)}>
        +
      </span>
      {show ? (
        <div className="add">
          <input
            type="text"
            ref={inp}
            placeholder="请输入待办事项..."
            onKeyDown={keySubmit}
          />
          <button style={{ outline: "none" }} onClick={submit}>
            增加
          </button>
        </div>
      ) : (
        ""
      )}
    </div>
  );
}
